<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单类别" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择工单类别" style="width: 160px" clearable>
          <el-option
            v-for="dict in asset_flow_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单号" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核结果" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择审核结果" style="width: 160px" clearable>
          <el-option
            v-for="dict in flow_check_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="流程进度" prop="flowStatus">
        <el-select v-model="queryParams.flowStatus" placeholder="请选择流程进度" style="width: 160px" clearable>
          <el-option
            v-for="dict in asset_flow_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资产分类" prop="cateId">          
        <el-tree-select v-model="queryParams.cateId" :data="categoryOptions" style="width: 240px"
          :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择分类" check-strictly />
      </el-form-item>
      
      <el-form-item label="申请部门" prop="deptId">
        <el-tree-select v-model="queryParams.deptId" :data="deptOptions"  style="width: 240px"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门" check-strictly />
      </el-form-item>
      <el-form-item label="申请人" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable  style="width: 160px">
            <el-option
              v-for="u in userOptions"
              :key="u.value"
              :label="u.label"
              :value="u.value"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="申请时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeApplyTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['asset:flow:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['asset:flow:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['asset:flow:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="flowList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单类别" align="center" prop="typeName"/>
      <el-table-column label="单号" align="center" prop="num" />
      <el-table-column label="资产编码" align="center" prop="assetNum" />
      <el-table-column label="资产分类" align="center" prop="cateName" />
      <el-table-column label="申请数量" align="center" prop="amount" />
      <el-table-column label="申请部门" align="center" prop="deptName" />
      <el-table-column label="申请人" align="center" prop="userName" />
      <el-table-column label="申请原由" align="center" prop="reason" />
      <el-table-column label="审核结果" align="center" prop="checkStatus">
        <template #default="scope">
          <dict-tag :options="flow_check_status" :value="scope.row.checkStatus"/>
        </template>
      </el-table-column>
      <!--
      <el-table-column label="流程进度" align="center" prop="flowStatus">
        <template #default="scope">
          <dict-tag :options="asset_flow_status" :value="scope.row.flowStatus"/>
        </template>
      </el-table-column>
      -->
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">详细</el-button>
          <el-button link type="primary" icon="Delete" v-if="scope.row.checkStatus != '1'" @click="handleDelete(scope.row)" v-hasPermi="['asset:flow:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资产工单对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="flowRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单类别" prop="type">
          <dict-tag :options="asset_flow_type" :value="form.type"/>
        </el-form-item>
        <el-form-item label="单号" prop="num">
          <el-input v-model="form.num" placeholder="请输入单号" readonly/>
        </el-form-item>
        <el-form-item label="申请数量" prop="amount"  v-if="form.type == 'P'">
          <el-input-number v-model="form.amount" placeholder="请输入申请数量" />
        </el-form-item>        
        <el-form-item label="申请资产" prop="assetId"  v-if="form.type != 'P'">
          <el-select 
            v-model="form.assetId"
            placeholder="请输入代码搜索"
            clearable filterable
            remote reserve-keyword
            :remote-method="assetLoad"
            :loading="assetLoading">
            <el-option
              v-for="dict in assetOptions"
              :key="dict.id"
              :label="dict.num + '('+dict.cateName+')'"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请原由" prop="reason">
          <el-input type="textarea" v-model="form.reason" placeholder="请输入申请原由" rows="3"/>
        </el-form-item>
        <el-form-item label="申请说明">
          <el-input type="textarea" v-model="form.content"  placeholder="请输入详细说明" rows="3"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <view-dialog :flowData="viewData" @close="cancelView"/>
  </div>
</template>

<script setup name="Flow">
import { listFlow, getFlow, delFlow, addFlow, updateFlow } from "@/api/asset/flow";
import { selectCategory } from "@/api/base/category";
import { selectInfo } from "@/api/asset/info";
import { queryDs } from "@/api/dev/dataset";
import ViewDialog from './view'

const { proxy } = getCurrentInstance();
const { asset_flow_type, flow_check_status, asset_flow_status } = proxy.useDict('asset_flow_type', 'flow_check_status', 'asset_flow_status');

const flowList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeApplyTime = ref([]);
const assetOptions = ref([]);
const assetLoading = ref(true);
const viewData = ref(null);
const categoryOptions = ref([]);
const deptOptions = ref([]);
const userOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'DESC',
    type: null,
    num: null,
    cateId: null,
    deptId: null,
    userId: null,
    checkStatus: null,
    flowStatus: null,
    applyTime: null
  },
  rules: {
    type: [
      { required: true, message: "工单类别不能为空", trigger: "change" }
    ],
    num: [
      { required: true, message: "单号不能为空", trigger: "blur" }
    ],
    cateId: [
      { required: true, message: "资产分类不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "申请部门不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "申请人不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "申请数量不能为空", trigger: "blur" }
    ],
    reason: [
      { required: true, message: "申请原由不能为空", trigger: "blur" }
    ],
    applyTime: [
      { required: true, message: "申请时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询资产工单列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeApplyTime && '' != daterangeApplyTime) {
    queryParams.value.params["beginApplyTime"] = daterangeApplyTime.value[0];
    queryParams.value.params["endApplyTime"] = daterangeApplyTime.value[1];
  }
  listFlow(queryParams.value).then(response => {
    flowList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    num: null,
    cateId: null,
    deptId: null,
    userId: null,
    amount: null,
    reason: null,
    content: null,
    checkStatus: null,
    flowStatus: null,
    applyTime: null
  };
  proxy.resetForm("flowRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeApplyTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 查看按钮操作 */
function handleView(row) {  
  viewData.value = row;
}
function cancelView() {
  viewData.value = null;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["flowRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFlow(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFlow(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资产工单编号为"' + _ids + '"的数据项？').then(function() {
    return delFlow(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('asset/flow/export', {
    ...queryParams.value
  }, `flow_${new Date().getTime()}.xlsx`)
}


/** 远程加载 */
function assetLoad(query){
  assetLoading.value = true;
  selectInfo({num:query, status:'1', pageSize:100}).then(response=>{
    assetOptions.value = response.data;
    assetLoading.value = false;
  });
}

getList();

selectCategory().then(response => {
  categoryOptions.value = [];
  const data = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy.handleTree(response.data, "id", "pid");
  categoryOptions.value.push(data);
});
queryDs({"code":"sys_user_select"}).then(response=>{
    userOptions.value = response.data;
});
queryDs({"code":"sys_dept_tree"}).then(response=>{
  deptOptions.value = proxy.handleTree(response.data, "id", "pid");
});
</script>
